<template>
  <div class="app-container calendar-list-container">

    <!-- 查询-->
    <el-card>
      <div class="block">
        <span style="color:gray; font-size:16px"> 时间范围: </span>

        <el-date-picker v-model="transactionQuery.timeInterval" type="datetimerange" :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" size="mini" align="right">
        </el-date-picker>
      </div>
      <div style="margin-bottom: 10px"></div>

      <el-select size="mini" clearable v-model="transactionQuery.modeId" placeholder="支付方式">
        <el-option v-for="pay in payData" :key="pay.id" :label="pay.modeName" :value="pay.id">
        </el-option>
      </el-select>
      <el-select size="mini" clearable v-model="transactionQuery.channelId" placeholder="应用渠道">
        <el-option v-for="pay in channelData" :key="pay.id" :label="pay.channelName" :value="pay.id">
        </el-option>
      </el-select>
      <el-input size="mini" clearable class="filter-item" style="width: 200px;" placeholder="支付流水" v-model="transactionQuery.outTradeNo">
      </el-input>
      <!-- <el-input size="mini" clearable class="filter-item" style="width: 200px;" placeholder="交易状态" v-model="transactionQuery.tradeStatus">
      </el-input> -->
      <div style="margin-bottom: 10px"></div>
      <el-input size="mini" clearable class="filter-item" style="width: 200px;" placeholder="终端号码" v-model="transactionQuery.terminalId">
      </el-input>

      <el-input size="mini" clearable class="filter-item" style="width: 200px;" placeholder="卡  号" v-model="transactionQuery.cardNo">
      </el-input>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="getList(1)" v-perm="'b:tr:tr:search'">搜索</el-button>
      <el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload" v-perm="'b:tr:tr:download'">导出</el-button>
    </el-card>
    <div style="margin-bottom: 10px"></div>
    <div :v-show="allStatistical">
      <el-tag type="success"> 交易 {{this.allStatistical.transactionNumber}} 笔订单</el-tag>
      <el-tag type="success">交易金额：{{this.allStatistical.allTotalFee}}</el-tag>
      <el-tag type="warning">退款金额： {{this.allStatistical.allRefundTotalFee}}</el-tag>
    </div>
    <div style="margin-bottom: 10px"></div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading.body="listLoading" id="transactionTable" element-loading-text="加载中" border fit highlight-current-row :default-sort="{prop: 'tradeDate', order: 'descending'}">

      <el-table-column align="center" label="应用" prop="channelName">
      </el-table-column>

      <el-table-column align="center" label="支付方式" prop="modeName">
      </el-table-column>

      <el-table-column align="center" label="流水号" prop="outTradeNo">
      </el-table-column>
      <el-table-column align="center" label="订单号" prop="tradeNo">
      </el-table-column>
      <el-table-column align="center" label="终端编号" prop="terminalId">
      </el-table-column>
      <el-table-column align="center" label="卡号" prop="cardNo">
      </el-table-column>
      <el-table-column align="center" label="姓名" prop="name">
      </el-table-column>
      <el-table-column align="center" label="交易金额" prop="totalFee">
      </el-table-column>
      <el-table-column align="center" label="交易类型" prop="tradeType" :formatter="formatRole">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.recType === 1">
            消费
          </el-tag>
          <el-tag type="danger" v-else-if="scope.row.recType === 2">
            退款
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="交易时间" :formatter="dateFormat" prop="tradeDate">
      </el-table-column>
      <el-table-column align="center" label="状态" prop="tradeStatus">
      </el-table-column>
      <el-table-column align="center" label="操作员姓名" prop="operatorName">
      </el-table-column>
      <el-table-column align="center" label="退款" >
        <template slot-scope="scope">
          <el-dropdown>
            <el-button type="warning" size="mini">
              操作
              <i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-button type="danger" size="mini" plain @click="handleRefund(scope.row)" v-if="scope.row.recType==1 && scope.row.outRequestNo==null">退 款</el-button>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="tablePage.page" :page-sizes="[10,20,30,50]" :page-size="tablePage.size" layout="total, sizes, prev, pager, next, jumper" :total="tablePage.total">
      </el-pagination>
    </div>

  </div>
</template>


<script>
import { queryPlatformBusinessRec, allStatistical, downBillDetail, refund } from '@/api/transaction'
import { pageParamNames } from '@/utils/constants'
import optionApi from '@/api/option'
export default {
  name: 'Transaction',
  data() {
    return {
      payData: [],
      channelData: [],
      payMap: new Map(),
      channelMap: new Map(),
      list: null,
      allStatistical: {
        transactionNumber: undefined,
        allTotalFee: undefined,
        allRefundTotalFee: undefined
      }, // 统计所有的数据
      listLoading: false,
      transactionQuery: {
        modeId: undefined, // 支付渠道
        channelId: undefined, //应用渠道
        cardNo: undefined, // 卡号
        terminalId: undefined, // 终端号
        outTradeNo: undefined, // 支付流水
        timeInterval: [
          new Date().setHours(0, 0, 0, 0) - 24 * 60 * 60 * 1000 * 3,
          new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000)
        ] // 支付间隔
      },
      listForm: {
        id: null,
        orgId: null,
        modeCode: null,
        modeName: null
      },
      tablePage: {
        current: null,
        pages: null,
        size: null,
        total: null
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '前天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 2)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 1)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  created() {
    this.getList()
    this.initData()
  },
  methods: {
    formatRole: function(row, column) {
      return row.recType === 1 ? '消费' : row.recType === 2 ? '退款' : '无'
    },
    dateFormat: function(row, column) {
      var date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return date.replace('T', ' ').substr(0, 19)
    },

    getList(current) {
      if (current) {
        this.tablePage.current = current
      }
      this.listLoading = true
      this.getAllStatistical()
      queryPlatformBusinessRec(this.transactionQuery, this.tablePage).then(res => {
        this.list = res.data.page.records
        this.listLoading = false
        pageParamNames.forEach(name => this.$set(this.tablePage, name, res.data.page[name]))
      })
    },

    handleRefund(row) {
      var refundParam = {
        id: row.id,
        orgId: row.orgId,
        channelId: row.channelId,
        modeId: row.modeId,
        outTradeNo: row.outTradeNo,
        refundFee: row.totalFee
      }
      this.$confirm('是否确认退款?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          refund(refundParam)
            .then(res => {
              // console.log(res.data.data)
              this.$message({
                type: 'success',
                message: res.data.data
              })
              this.getList()
            })
            .catch(() => {
              this.$message({
                type: 'error',
                message: '退款失败!'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '退款取消'
          })
        })
    },

    getAllStatistical() {
      allStatistical(this.transactionQuery).then(res => {
        // console.log('allStatistical', res.data.allStatistical)
        var transactionNumber = 0
        var allTotalFee = 0
        var allRefundTotalFee = 0
        var allStatistical = res.data.allStatistical
        for (var j = 0; j < allStatistical.length; j++) {
          var tempObj = allStatistical[j]
          transactionNumber += tempObj.transactionNumber
          if (tempObj.recType === 2) {
            allRefundTotalFee += tempObj.allTotalFee
          }
          if (tempObj.recType === 1) {
            allTotalFee += tempObj.allTotalFee
          }
        }
        this.allStatistical.transactionNumber = transactionNumber
        this.allStatistical.allRefundTotalFee = allRefundTotalFee
        this.allStatistical.allTotalFee = allTotalFee
      })
    },

    handleSizeChange(val) {
      this.tablePage.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.tablePage.current = val
      this.getList()
    },
    handleDownload() {
      this.listLoading = true
      // var wb = XLSX.utils.table_to_book(document.querySelector('#transactionTable'))
      // var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      // try {
      //   FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '交易明细.xlsx')
      // } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
      // this.listLoading = false
      // return wbout

      import('@/vendor/Export2Excel').then(excel => {
        downBillDetail(this.transactionQuery).then(response => {
          console.log(response.data.map)
          if (response.data.map.size === 0) {
            this.$message({
              showClose: true,
              message: '提示，无内容可下载',
              type: 'warning'
            })
            this.listLoading = false
          }else{
          const tHeader = [
            'id',
            '应用渠道',
            '支付方式',
            '流水号',
            '订单号',
            '终端编号',
            '卡号',
            '用户姓名',
            '交易金额',
            '交易类型',
            '交易时间',
            '状态',
            '操作员姓名'
          ]
          const filterVal = [
            'id',
            'channelName',
            'modeName',
            'outTradeNo',
            'tradeNo',
            'terminalId',
            'cardNo',
            'name',
            'totalFee',
            'recType',
            'tradeDate',
            'tradeStatus',
            'operatorName'
          ]
          var lists = response.data.map.list
          for (var i = 0; i < lists.length; i++) {
            if (lists[i].recType === 1) lists[i].recType = '消费'
            else if (lists[i].recType === 2) lists[i].recType = '退款'
          }
          excel.export_json_to_excel2(tHeader, lists, filterVal, response.data.map.start+'至'+response.data.map.end+'交易明细单')
          this.listLoading = false
          }
        })
      })
    },

    initData() {
      optionApi.show().then(res => {
        res.data.payOptions.forEach(obj => {
          this.payData.push(obj)
          this.payMap.set(obj.id, obj.modeName)
        })
      }),
        optionApi.showChannel().then(res => {
          res.data.acOptions.forEach(obj => {
            this.channelData.push(obj)
            this.channelMap.set(obj.id, obj.channelName)
          })
        })
    }
  }
}
</script>
